<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表v-loading="listLoading"-->
		<el-table :data="tableDatas" v-loading="listLoading" @selection-change="handleSelectionChange" highlight-current-row
			style="width: 100%;">
			<!--多选框-->
			<el-table-column type="selection" >
			</el-table-column>
			<el-table-column type="index" width="70" label="序号">
			</el-table-column>
			<el-table-column prop="realName" label="真实姓名" >
			</el-table-column>
			<el-table-column prop="userName" label="登录账号" >
			</el-table-column>
			<el-table-column prop="phone" label="手机号" >
			</el-table-column>
			<el-table-column prop="email" label="邮箱">
			</el-table-column>
			<el-table-column prop="remark" label="备注"  show-overflow-tooltip>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" :disabled="this.sels.length === 0" @click="handlePatchDel">批量删除</el-button>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
				:page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="totals" style="float:right;">
			</el-pagination>
		</el-col>
<!--
  添加或修改页面
  visible.sync: 是否显示模态框
  :close-on-click-model:点空白处是否关模态框
  :rules="saveFormRules" form表单校验规则
  ref="saveForm" form表单的id
 -->
		<!--添加或修改界面-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm" >
				<el-form-item label="用户名称" prop="userName">
					<el-input v-model="saveForm.userName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="真实姓名">
					<el-input v-model="saveForm.realName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="手机号码" prop="phone">
					<el-input v-model="saveForm.phone" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱地址">
					<el-input v-model="saveForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="登录密码" v-if="saveForm.id == null" prop="password">
					<el-input type="password" v-model="saveForm.password" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="确认密码" v-if="saveForm.id == null" prop="cpassword">
          <el-input type="password" v-model="saveForm.cpassword" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="备注信息">
					<el-input v-model="saveForm.remark" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

import {title} from "mockjs/src/mock/random/text";

export default {
	data() {
    var validatePhone = (rule, value, callback) => {
      const regex = /^(\+?d{1,4}?)?[1-9]\d{10}$/;
      console.log(regex.test(value))
      if(regex.test(value)){
        /*放行*/
        callback();
      }else {
        callback(new Error("请输入正确的电话号码"));
      }
    };

    var validateUserName = (rule, value, callback) => {
      let param = {
        userName:value,
        id:this.saveForm.id
      }
      this.$http.post("/user/exist",param).then(res=>{
        let {success,resultObj} = res.data;
        if(success){
          if(resultObj){
            callback();
          }else{
            callback(new Error('用户名已存在'));
          }
        }
      })
    };
    var validateCPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.saveForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.saveForm.checkPass !== '') {
          this.$refs.saveForm.validateField('cpassword');
        }
        callback();
      }
    };
		return {

			//1.分页查询相关数据
			totals: 0,//总记录条数
			currentPage: 1,//当前页,要传递到后台的
			pageSize: 5, //每页显示多少条
			tableDatas: [], //当前页数据
			listLoading: false,
      //模态框标题
      title:"",
			//2.高级查询相关数据
			keyword: '',

			//3.删除相关数据

			//4.批量删除相关数据
			sels: [], //存储多选记录

			//5.添加和修改相关数据
			saveFormVisible: false,
			saveForm: {
				id: null,
				userName: '',
				realName: '',
				email: '',
				password: '', //后端需要通过md5加密
        cpassword:"", //确认密码
				remark: '',
				phone: ''
				//avatar头像 - 前端没有传递 - 需要文件上传
				//logininfo_id - 后端业务生成
			},

			//6.添加和修改校验规则-表单项校验
			saveFormRules: {
				userName: [
					{ required: true, message: '请输入用户名称', trigger: 'blur' },
          { validator: validateUserName, trigger: 'blur'  }
				],
				phone: [
					{ required: true, message: '请输入电话号码', trigger: 'blur' },
          {validator: validatePhone,trigger:'blur'}
				],
				password: [
					/*{ required: true, message: '请输入登录密码', trigger: 'blur' },*/
          {validator: validatePass,trigger:'blur'}
				],
        cpassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {validator: validateCPassword,trigger:'blur'}
        ]
			},

		}
	},
	methods: {
		//1.分页查询相关方法
		//1.1.获取列表数据
		getTableData() {
      //开启加载框
      this.listLoading = true;
			let param = {
        //keyword是用来进行关键字查询的 默认为空 因为关键词查询也会进行分页 所以这里需要keyword  key是为了和后端的一致
        "key":this.keyword,
        "currentPage": this.currentPage,
        "pageSize":this.pageSize
      }
      this.$http.patch("/user",param).then(res=>{
        let {success,resultObj} = res.data;
        if(success){
           //关闭加载框
          this.listLoading = false;
          this.tableDatas = resultObj.list;
          this.totals = resultObj.total;
        }
      })
		},
		//1.2.选择第几页时触发
		handleCurrentChange(curentPage) {
			this.currentPage = curentPage;
      this.getTableData();
		},
		//1.3.选择每页显示记录条数时触发
		handleSizeChange(pageSize) {
			  this.currentPage = 1;
        this.pageSize = pageSize;
        this.getTableData();
		},

		//2.高级查询相关方法
		keywordQuery() {
      //根据关键字查询的时候 首先需要把当前页收缩成第一页
			this.currentPage = 1;
      this.getTableData();
		},

		//3.删除相关方法
		handleDel(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/user/"+row.id).then(res=> {
          let {success} = res.data;
          if (success) {
            this.$message({
              type: 'success',
              message: "删除成功！"
            });
            //删除成功过后需要刷新
            this.getTableData();
          }else {
            this.$message.error(message);
          }
        })
      });
		},


		//4.批量删除相关方法
		//4.1.选项改变时触发
		handleSelectionChange(val) {
      this.sels = val;
		},
		//4.2.批量删除
    handlePatchDel() {
      this.$confirm('您确认删除选中的数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.patch("/user/patchDelete",this.sels).then(res=>{
          let  {success} = res.data;
          if(success){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getTableData();
          }
        })
      });
    },

		//5.添加和修改相关方法
		//5.1.点击添加弹出对话框
		handleAdd() {
      //设置标题
      this.title = "新增用户";
      //清空表单
      for(let k in this.saveForm){
        this.saveForm[k] = "";
      }
      //新增应该显示密码框
      this.saveForm["id"] = null;
      //清空校验
      if( this.$refs["saveForm"]){
        this.$refs["saveForm"].clearValidate();
      }
      //弹出窗体
			 this.saveFormVisible = true;
		},
		//5.2.点击修改弹出对话框
		handleEdit(row) {
      //修改标题
      this.title = "编辑用户";
      //清空表单
      for(let k in this.saveForm){
        this.saveForm[k] = "";
      }
    //回显数据
      for(let k in row){
        this.saveForm[k] = row[k];
      }
      //清空校验
      if( this.$refs["saveForm"]){
        this.$refs["saveForm"].clearValidate();
      }
    //打开模态框
      this.saveFormVisible = true
		},
		//5.3.提交表单数据操作数据库
		saveSubmit() {
      this.$refs["saveForm"].validate((valid) => {
        if (valid) {
          this.$http.post("/user",this.saveForm).then(res=>{
            let {success} = res.data;
            if(success){
              this.saveFormVisible = false;
              this.getTableData();
            }
          })
        }
      });
		},
	},
	mounted() {
		this.getTableData();
	}
}

</script>

<style scoped></style>
